package com.gdones.common.core.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 拼音工具类
 * 2023/5/5
 */
public class MyPinYinUtil {

    private MyPinYinUtil(){}

    private static HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();

    static{
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        outputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
        outputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
    }

    /**
     * 将中文字符串转换为汉语拼音大写
     * @param str
     * @return
     */
    public static String getPinYinByString(String str){

        String resStr = "";

        char[] charArray = str.toCharArray();

        for(char temp:charArray){
            String[] hanyuPinyinStringArray = new String[0];
            try {
                hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(temp, outputFormat);
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
            String s = concatPinyinStringArray(hanyuPinyinStringArray);
            if(s == null){
                resStr += "";
            }else if(s.equals("")){
                resStr += "";
            }else{
                resStr += (s.substring(0,1));
            }

        }

        return resStr.replaceAll(" +","");
    }

    private static String concatPinyinStringArray(String[] pinyinArray)
    {
        StringBuffer pinyinStrBuf = new StringBuffer();
        if ((null != pinyinArray) && (pinyinArray.length > 0))
        {
            for (int i = 0; i < pinyinArray.length; i++)
            {
                pinyinStrBuf.append(pinyinArray[i]);
            }
        }
        String outputString = pinyinStrBuf.toString();
        return outputString;
    }

}
